<?php
/* 上传文件归属 */
define('BELONG_ARTICLE',    1);
define('BELONG_GOODS',      2);
define('BELONG_STORE',      3);


define('PRIVATEKEY', "yj888128");

/* 设置消息接收 */
set_error_handler('exception_handler');
if(!function_exists('file_rput_contents')) {
    function file_rput_contents($file, $content, $flags = 0) {
        $dir = dirname($file);
        is_dir($dir) or mkdir($dir, 0777, true);
        file_put_contents($file, $content, $flags);
    }
}
/**
 * Exception Handler
 *
 * error:   中断程序，提示信息中出现报告bug的链接以及记录到日志文件
 * warning: 中断程序，提示信息中出现报告bug的链接。
 * notice:  不中断程序，错误信息输出到页面的注释中
 *---------------------------------------
 * 用户级的错误处理方式：
 *
 * error:   中断程序，提示信息中出现报告bug的链接以及记录到日志文件
 * warning: 中断程序，提示信息中不包括出错文件及行号等信息
 * notice:  中断程序，提示信息中不包括出错文件及行号等信息。 如何处理链接地址呢？
 *---------------------------------------
 *
 * @param   number  $errno
 * @param   string  $errstr
 * @param   string  $errfile
 * @param   string  $errline
 *
 * @return  void
 */
function exception_handler($errno, $errstr, $errfile, $errline)
{
	if ($errno == 2048 || (($errno & error_reporting()) != $errno))
	{
		//不再需要通过_at方法来抵制错误
		//错误被屏蔽时就不抛出异常，该处理就允许你在代码中照常使用error_reporting来控制错误报告
		return true;
	}

	if ($errno != E_NOTICE)
	{
		$errfile    = str_replace(ROOT_PATH, '', $errfile);

		if ($errno != E_USER_WARNING && $errno != E_USER_NOTICE)
		{
			$status=" | errno=".$errno." | errstr=".$errstr." | errfile=".$errfile." | errline=".$errline;
		}

		/* add report link */
		if ($errno == E_USER_ERROR || $errno == E_ERROR || $errno == E_PARSE || $errno == E_WARNING)
		{
			put_log($errno, $errstr, $errfile, $errline); // 写入错误日志
			throw new Exception($status);
		}
		else
		{
			throw new Exception($status);
		}
	}
	else if ($errno == E_NOTICE && (defined('DEBUG_MODE') && DEBUG_MODE & E_NOTICE) )
	{
		$status=" | errno=".$errno." | errstr=".$errstr." | errfile=".$errfile." | errline=".$errline;
		throw new Exception($status);
	}
	return true;
}

function checkUrl($url, $timeout = 15){
	$ret = false;
	$handle = curl_init();
	curl_setopt($handle, CURLOPT_URL,$url);
	curl_setopt($handle, CURLOPT_NOBODY, true);
	curl_setopt($handle, CURLOPT_TIMEOUT,$timeout);//设置默认超时时间为3秒
	$result = curl_exec($handle);
	//$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
	//curl_close($handle);
	if($result){
		$ret = true;
	}
	return $ret;
}

/**
 * 写入 log 文件
 *
 * @param   string  $msg
 * @param   string  $file
 * @param   string  $line
 */
function put_log($err, $msg, $file, $line)
{
	$filename = ROOT_PATH . "/temp/logs/" .date("Ym"). ".log";

	if (!is_dir('temp/logs'))
	{
		ecm_mkdir(ROOT_PATH . '/' . 'temp/logs');
	}

	$handler = null;

	if (($handler = fopen($filename, 'ab+')) !== false)
	{
		fwrite($handler, date('r') . "\t[$err]$msg\t$file\t$line\n");
		fclose($handler);
	}
}

function JSONResult($status,$list,$pars) {
    $reval = array("status"=>$status,
        "result"=>$list,
        "uid"=>empty($pars)||!property_exists($pars,'uid')?0:$pars->uid,
        "version"=>empty($pars)||!property_exists($pars,'version')?"":$pars->version,
        "system"=>empty($pars)||!property_exists($pars,'system')?"":$pars->system,
        "opdt"=>local_date("YmdHis"),
        "rnd"=>get_total_millisecond()
    );
	return JSON($reval);
}

function JSONResult2($status,$list) {
	$reval=array("status"=>$status,
		"result"=>$list
	);
	return JSON($reval);
}
/**************************************************************
 *
 *	将数组转换为JSON字符串（兼容中文）
 *	@param	$array		要转换的数组
 *	@return string		转换得到的json字符串
 *	@access public
 *
 *************************************************************/
function JSON($array) {
	return json_encode_cn($array);
}

/**
 * json_encode 中文版
 */
if(!function_exists('json_encode_cn')) {
    function json_encode_cn($data) {
        return urldecode(json_encode(r_urlencode($data)));
    }
}

/**
 * 递归 urlencode
 * @param $data
 *
 */
if(!function_exists('r_urlencode')) {
    function r_urlencode($data)
    {
        if (is_array($data) || is_object($data)) {
            return array_map(function ($val) {
                return is_string($val) ? r_urlencode($val) : $val;
            }, $data);
        } else {
            return urlencode(addslashes($data));
        }
    }
}
/**************************************************************
 *
 *	使用特定function对数组中所有元素做处理
 *	@param	string	&$array		要处理的字符串
 *	@param	string	$function	要执行的函数
 *	@return boolean	$apply_to_keys_also		是否也应用到key上
 *	@access public
 *
 *************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
	static $recursive_counter = 0;
	if (++$recursive_counter > 1000) {
		die('possible deep recursion attack');
	}
	foreach ($array as $key => $value) {
		if (is_array($value)) {
			arrayRecursive($array[$key], $function, $apply_to_keys_also);
		} else {
			$array[$key] = $function($value);
		}

		if ($apply_to_keys_also && is_string($key)) {
			$new_key = $function($key);
			if ($new_key != $key) {
				$array[$new_key] = $array[$key];
				unset($array[$key]);
			}
		}
	}
	$recursive_counter--;
}

/**
 * 获得当前格林威治时间的时间戳
 *
 * @return  integer
 */
function gmtime()
{
	return time();      // 时间戳
}
function local_date($format, $time = NULL)
{
	/* 现在暂时还没有用户自定义时区的功能，所有的时区都跟着商城的设置走 */
	$timezone = 8;

	if ($time === NULL)
	{
		$time = gmtime();
	}
	elseif ($time <= 0)
	{
		return '';
	}

	$time += ($timezone * 3600);

	return date($format, $time);
}
function gmstr2time($str)
{
	$time = strtotime($str);

	if ($time > 0)
	{
		$time -= date('Z');
	}

	return $time;
}
function get_total_millisecond()
{
	$time = explode (" ", microtime () );
	$time = $time [1] . ($time [0] * 1000);
	$time2 = explode ( ".", $time );
	$time = $time2 [0];
	return $time;
}
/**
 * 加密
 * @param string $str 要处理的字符串
 * @param string $key 加密Key，为8个字节长度
 * @return string
 */
function encrypt($string) {
	//01234567
	$ivArray=array(0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37);
	$iv=null;
	foreach ($ivArray as $element)
	$iv.=CHR($element);
	$size = mcrypt_get_block_size( MCRYPT_DES, MCRYPT_MODE_CBC );
	$pad = $size - (strlen( $string ) % $size);
	$string .= str_repeat( chr( $pad ), $pad );
	$data =  mcrypt_encrypt(MCRYPT_DES, PRIVATEKEY, $string, MCRYPT_MODE_CBC, $iv);
	$data = base64_encode($data);
	return $data;
}
/**
 * 解密
 * @param string $str 要处理的字符串
 * @param string $key 解密Key，为8个字节长度
 * @return string
 */
function decrypt($string) {
	//$ivArray=array(0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF);
	//01234567
	$ivArray=array(0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37);
	$iv=null;
	foreach ($ivArray as $element)
	$iv.=CHR($element);
	$string = base64_decode($string);
	$string =  mcrypt_decrypt(MCRYPT_DES, PRIVATEKEY, $string, MCRYPT_MODE_CBC, $iv);
	$pad = ord ( $string {strlen ( $string ) - 1} );
	if ($pad > strlen ( $string ))
	return false;
	if (strspn ( $string, chr ( $pad ), strlen ( $string ) - $pad ) != $pad)
	return false;
	return substr ( $string, 0, - 1 * $pad );
}
/**
 * 地区名称转id
 * @param unknown_type $r
 * @throws Exception
 */
function regionId($r){
	$province=$r->province?$r->province:'';
	$city=$r->city?$r->city:'';
	$district=$r->district?$r->district:'';
	$street=$r->street?$r->street:'';

	$region=&m('region');
	$region_p=$region->get("region_name='".$province."'");
	if(empty($region_p)){
		throw new Exception($province.'暂不在服务范围');
	}
	$region_c=$region->get("region_name='".$city."' and parent_id=".$region_p['region_id']);
	if(empty($region_c)){
		throw new Exception($city.'暂不在服务范围');
	}

	$region_d=$region->get("region_name='".$district."' and parent_id=".$region_c['region_id']);
	if(empty($region_d)){
		throw new Exception($district.'暂不在服务范围');
	}

	$region_s=$region->get("region_name='".$street."' and parent_id=".$region_d['region_id']);
	if(empty($region_c)){
		throw new Exception($street.'暂不在服务范围');
	}

	$regions = array('province'=>$region_p['region_name'],'p'=>$region_p['region_id'],'c'=>$region_c['region_id'],'city'=>$region_c['region_name'],'district'=>$region_d['region_name'],'d'=>$region_d['region_id'],'street'=>$region_s['region_name'],'s'=>$region_s['region_id']);
	return $regions;
}

/**
 * 写订单进程
 * @param unknown_type $op_otid
 * @param unknown_type $op_status
 * @param unknown_type $op_uid
 * @param unknown_type $op_note
 * @param unknown_type $op_pic
 * @throws Exception
 */
function order_progress($order_id,$order_status,$changed_status,$user_id,$remark){
	$db=&db();
	$sql="select user_id,user_name,real_name from cw_member where user_id=".$user_id;
	$user=$db->getRow($sql);
	if(empty($user)){
		exit();
	}
	$operator=empty($user['real_name'])?$user['user_name']:$user['real_name'];
	$sql="insert into cw_order_log set
		order_id='".$order_id."',
		order_status='".$order_status."',
		changed_status='".$changed_status."',
		log_time='".gmtime()."',
		operator='".$operator."',
		remark='".$remark."'";

	$db->query($sql,'SILENT');
}


function  Directory( $dir ){
	return   is_dir ( $dir )  or  (Directory(dirname( $dir ))  and   mkdir ( $dir , 0777));
}
/**
 * 上传图片文件
 * @param file $file 文件
 * @param unknown_type $path 路径
 * @param unknown_type $isthum 是否略缩
 * @param unknown_type $thumwidth 略缩宽
 * @param unknown_type $thmheight 略缩高
 */
function fileupload($file,$path,$prefs='',$itemid=0,$isthum=FALSE,$thumwidth=280,$thumheight=0,$thumquality=50){
	$allowpictype = array('jpg','jpeg','gif','png');
	if(!empty($file)){
		//判断后缀
		$fileext = strtolower(trim(substr(strrchr($file['name'], '.'), 1)));

		if(!in_array($fileext, $allowpictype)) {
			throw new Exception("不允许的文件格式！");
		}

		if($file['size']>1024*100){
			throw new Exception("上传的文件大小不要超过100K！");
		}

		//本地上传
		$new_name = '../'.$path.'/'.$prefs.$itemid.'/';
		if (!is_dir($new_name)){
			if(@!Directory($new_name, 0777)){
				throw new Exception("创建图片目录失败！");
			}
		}

		$fname=str_replace(".",'',microtime(1));
		$new_name.=$fname.'.'.$fileext;
		$path=$path.'/'.$prefs.$itemid.'/'.$fname.'.'.$fileext;

		$tmp_name = $file['tmp_name'];
		if(@copy($tmp_name, $new_name)) {
			@unlink($tmp_name);
		} elseif((function_exists('move_uploaded_file') && @move_uploaded_file($tmp_name, $new_name))) {
		} elseif(@rename($tmp_name, $new_name)) {
		} else {
			throw new Exception("无法转移临时图片到服务器指定目录！");
		}

		//检查是否图片
		if(function_exists('getimagesize')) {
			$tmp_imagesize = @getimagesize($new_name);
			list($tmp_width, $tmp_height, $tmp_type) = (array)$tmp_imagesize;
			$tmp_size = $tmp_width * $tmp_height;
			if($tmp_size > 16777216 || $tmp_size < 4 || empty($tmp_type) || strpos($tmp_imagesize['mime'], 'flash') > 0) {
				@unlink($new_name);
				throw new Exception("只可以上传图片类型的文件！");
			}
		}

		if($isthum){
			$thumbnail = dirname($new_name) . '/' . basename($new_name).'.thumb.jpg';
			include_once('../data/image.func.php');
			make_thumb(ROOT_PATH.'/'.$path, $thumbnail,
		 $thumwidth, $thumheight, $thumquality);
		 return $thumbnail;
		}
		return $path;
	}else{
		throw new Exception("文件不存在！");
	}
}

/**
 * 上传语音文件
 * @param file $file 文件
 * @param unknown_type $path 路径
 * @param unknown_type $isthum 是否略缩
 * @param unknown_type $thumwidth 略缩宽
 * @param unknown_type $thmheight 略缩高
 */
function fileuploadAudio($file,$path,$prefs='',$itemid=0){
	$allowtype = array('amr');
	if(!empty($file)){
		//判断后缀
		$fileext = strtolower(trim(substr(strrchr($file['name'], '.'), 1)));

		if(!in_array($fileext, $allowtype)) {
			throw new Exception("不允许的文件格式！");
		}

		if($file['size']>1024*1024*20){
			throw new Exception("上传的文件大小不要超过2M！");
		}

		//本地上传
		$new_name = '../'.$path.'/'.$prefs.$itemid.'/';
		if (!is_dir($new_name)){
			if(@!Directory($new_name, 0777)){
				throw new Exception("创建目录失败！");
			}
		}

		$fname=str_replace(".",'',microtime(1));
		$new_name.=$fname.'.'.$fileext;
		$path=$path.'/'.$prefs.$itemid.'/'.$fname.'.'.$fileext;

		$tmp_name = $file['tmp_name'];
		if(@copy($tmp_name, $new_name)) {
			@unlink($tmp_name);
		} elseif((function_exists('move_uploaded_file') && @move_uploaded_file($tmp_name, $new_name))) {
		} elseif(@rename($tmp_name, $new_name)) {
		} else {
			throw new Exception("无法转移临时文件到服务器指定目录！");
		}
		return $path;
	}else{
		throw new Exception("文件不存在！");
	}
}

/**
 * 更新用户评分
 * @param unknown_type $uid
 * @throws Exception
 */
function userscore($uid){
	$member_mod=&m('member');
	$sql="select m.user_id from yk_member m inner join yk_doctor d on m.user_id=d.user_id where del=0 and m.user_id=".$uid;
	$member=$member_mod->db->getRow($sql);
	if($member){
		/*$sql="
		 select ROUND(sum(s)/COUNT(id),1) from(
		 SELECT yc_tid as id,yc_scoreuid as s FROM yk_complain where yc_uid=".$member['user_id']."
		 UNION
		 SELECT yc_tid as id,yc_scoretouid as s FROM yk_complain where yc_touid=".$member['user_id']."
		 UNION
		 SELECT oe_tid as id,oe_score as s from yk_order_xiche_evaluate where oe_foruserid=".$member['user_id']."
		 ) x";*/
		$sql="select a.oe_foruserid,ROUND(IFNULL(g,1)/IFNULL(t,1),4) as p from (
select oe_foruserid,COUNT(1) as t from yk_order_evaluate WHERE oe_foruserid=$uid GROUP BY oe_foruserid) a
LEFT JOIN(
select oe_foruserid,COUNT(1) as g from yk_order_evaluate WHERE oe_foruserid=$uid and IFNULL(oe_level,'好评')='好评' GROUP BY oe_foruserid) b on a.oe_foruserid=b.oe_foruserid
		";
		$level=100;
		$s=$member_mod->db->getRow($sql);
		if(!empty($s)){
			$level=$s['p']*100;
		}

		$sql="update yk_doctor set yd_credit='".$level."' where user_id=".$uid;
		$member_mod->db->query($sql);
	}
}

/**
 * 更新用户单数和等级
 * @param unknown_type $uid
 */
function usergrade($uid){
	$member_mod=&m('member');
	$sql="select user_id,user_type from yk_member where user_id=".$uid;
	$member=$member_mod->db->getRow($sql);
	if($member){
		$sql="select count(1) from yk_order_xiche where (o_status='已完成' or o_status='洗车完成') and (o_uid=".$member['user_id']." or o_waiter=".$member['user_id'].")";
		$s=$member_mod->db->getOne($sql);
		if(empty($s)){
			$s=0;
		}

		$sql="select * from yk_member_grade where ymg_orders<=".$s." and ymg_type='".$member['user_type']."' order by ymg_orders desc limit 1";
		$g=$member_mod->db->getRow($sql);

		$user_level='';
		if($g){
			$user_level=$g['ymg_name'];
		}
		$sql="update yk_member set order_num='".$s."',user_level='".$user_level."' where user_id=".$uid;
		$member_mod->db->query($sql);
	}
}

/**
 * 更新商铺
 * @param unknown_type $uid
 * @throws Exception
 */
function updatestore($store_id){
	$db=&db();
	$store_id=empty($store_id)?0:intval($store_id);
	if($store_id){
		$sql="select COUNT(1) from cw_order_goods g
INNER JOIN cw_order o on g.order_id=o.order_id
where seller_id=".$store_id." and evaluation_status=1";

		$evaluation_count=$db->getOne($sql);

		$sql="select COUNT(1) from cw_order_goods g
INNER JOIN cw_order o on g.order_id=o.order_id
where seller_id=".$store_id." and evaluation_status=1 and credit_value>=3";

		$praise_count=$db->getOne($sql);

		$praise_rate=round(($praise_count / $evaluation_count), 4) * 100;

		$sql="select SUM(credit_value)/COUNT(1) from cw_order_goods g
INNER JOIN cw_order o on g.order_id=o.order_id
where seller_id=".$store_id." and evaluation_status=1";

		$star=$db->getOne($sql);
		$star=round($star, 2);

		$sql="update cw_store set praise_rate='".$praise_rate."',star='".$star."' where store_id=".$store_id;
		$db->query($sql);
	}
}

/**
 * 获取字典值对
 * @param unknown_type $code
 * @throws Exception
 */
function getdic($code){
	$list=array();
	$dictionary =&m('dictionary');
	if(!empty($code)){
		$list=array_values($dictionary->find(array(
		       'fields'=>"d_key,d_value,d_assist",
			   'conditions'=>"d_code='".$code."' and ifnull(d_del,0)=0",
		        'order'   => 'd_order ASC')));
	}
	return $list;
}

/**
 * 发送短信
 * @param unknown_type $content
 * @param unknown_type $mobile
 * @throws Exception
 */
function smsSend($content,$mobile){
	$url='http://smsapi.c123.cn/OpenPlatform/OpenApi';           //接口地址
	$ac='1001@501215700001';		                             //用户账号
	$authkey = '4029274039014CEB443AAC4FD4DB4880';		         //认证密钥
	$cgid='5427';                                                  //通道组编号
	$c = $content;		 //内容
	$m= $mobile;	                                         //号码
	$csid='3';                                                   //签名编号 ,可以为空时，使用系统默认的编号
	$t='';
	sendSMS($url,$ac,$authkey,$cgid,$m,$c,$csid,$t);
}

//短信发送接口
function sendSMS($url,$ac,$authkey,$cgid,$m,$c,$csid,$t)
{
	$data = array
	(
		'action'=>'sendOnce',                                //发送类型 ，可以有sendOnce短信发送，sendBatch一对一发送，sendParam	动态参数短信接口
		'ac'=>$ac,					                         //用户账号
		'authkey'=>$authkey,	                             //认证密钥
		'cgid'=>$cgid,                                       //通道组编号
		'm'=>$m,		                                     //号码,多个号码用逗号隔开
		'c'=>$c,		                 //如果页面是gbk编码，则转成utf-8编码，如果是页面是utf-8编码，则不需要转码
		'csid'=>$csid,                                       //签名编号 ，可以为空，为空时使用系统默认的签名编号
		't'=>$t                                              //定时发送，为空时表示立即发送
	);
	$xml= postSMS($url,$data);			                     //POST方式提交
	$re=simplexml_load_string(utf8_encode($xml));
//	$file = fopen("err_log.txt","w");
//	fwrite($file,json_encode($data));
	
//	$file = fopen("err_log1.txt","w");
//	fwrite($file,json_encode($re));
	if(trim($re['result'])==1)                               //发送成功 ，返回企业编号，员工编号，发送编号，短信条数，单价，余额
	{
		foreach ($re->Item as $item)
		{
			$stat['msgid'] =trim((string)$item['msgid']);
			$stat['total']=trim((string)$item['total']);
			$stat['price']=trim((string)$item['price']);
			$stat['remain']=trim((string)$item['remain']);
			$stat_arr[]=$stat;

		}
		if(is_array($stat_arr))
		{
			//echo "发送成功,返回值为".$re['result'];
		}

	}
	else  //发送失败的返回值
	{
		$file = fopen("err_log.txt","w");
		fwrite($file,trim($re['result']));
		/*switch(trim($re['result'])){
			case  0: echo "帐户格式不正确(正确的格式为:员工编号@企业编号)";break;
			case  -1: echo "服务器拒绝(速度过快、限时或绑定IP不对等)如遇速度过快可延时再发";break;
			case  -2: echo " 密钥不正确";break;
			case  -3: echo "密钥已锁定";break;
			case  -4: echo "参数不正确(内容和号码不能为空，手机号码数过多，发送时间错误等)";break;
			case  -5: echo "无此帐户";break;
			case  -6: echo "帐户已锁定或已过期";break;
			case  -7:echo "帐户未开启接口发送";break;
			case  -8: echo "不可使用该通道组";break;
			case  -9: echo "帐户余额不足";break;
			case  -10: echo "内部错误";break;
			case  -11: echo "扣费失败";break;
			default:break;
			}*/
	}
}

function postSMS($url,$data='')
{
	$row = parse_url($url);
	$host = $row['host'];
	$post='';
	$port = @$row['port'] ? $row['port']:80;
	$file = $row['path'];
	while (list($k,$v) = each($data))
	{
		$post .= rawurlencode($k)."=".rawurlencode($v)."&";	//转URL标准码
	}
	$post = substr( $post , 0 , -1 );
	$len = strlen($post);
	$fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
	if (!$fp) {
		return "$errstr ($errno)\n";
	} else {
		$receive = '';
		$out = "POST $file HTTP/1.0\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Content-type: application/x-www-form-urlencoded\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Content-Length: $len\r\n\r\n";
		$out .= $post;
		fwrite($fp, $out);
		while (!feof($fp)) {
			$receive .= fgets($fp, 128);
		}
		fclose($fp);
		$receive = explode("\r\n\r\n",$receive);
		unset($receive[0]);
		return implode("",$receive);
	}
}

function postXML($url,$xml_data='')
{
	$ch = curl_init();
	$header[] = "Content-type: text/xml";//定义content-type为xml
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
	$response = curl_exec($ch);
	if(curl_errno($ch))
	{
		print curl_error($ch);
	}
	curl_close($ch);
}

function gen_order_sn()
{
	/* 选择一个随机的方案 */
	mt_srand((double) microtime() * 1000000);
	$timestamp = gmtime();
	$y = date('y', $timestamp);
	$z = date('z', $timestamp);
	$order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

	$model_order =& m('order');
	$orders = $model_order->find('order_sn=' . $order_sn);
	if (empty($orders))
	{
		/* 否则就使用这个订单号 */
		return $order_sn;
	}

	/* 如果有重复的，则重新生成 */
	return gen_order_sn();
}

function order_status_translator($order_status_text)
{
	switch ($order_status_text)
	{
		case 'canceled':    //已取消的订单
			return ORDER_CANCELED;
			break;
		case 'all':         //所有订单
			return '';
			break;
		case 'pending':     //待付款的订单
			return ORDER_PENDING;
			break;
		case 'submitted':   //已提交的订单
			return ORDER_SUBMITTED;
			break;
		case 'accepted':    //已确认的订单，待发货的订单
			return ORDER_ACCEPTED;
			break;
		case 'shipped':     //已发货的订单
			return ORDER_SHIPPED;
			break;
		case 'finished':    //已完成的订单
			return ORDER_FINISHED;
			break;
		default:            //所有订单
			return '';
			break;
	}
}
function order_status($order_status)
{
	$lang_key = '';
	switch ($order_status)
	{
		case ORDER_PENDING:
			$lang_key = '待付款';
			break;
		case ORDER_SUBMITTED:
			$lang_key = '已提交';
			break;
		case ORDER_ACCEPTED:
			$lang_key = '待发货';
			break;
		case ORDER_SHIPPED:
			$lang_key = '已发货';
			break;
		case ORDER_FINISHED:
			$lang_key = '已完成';
			break;
		case ORDER_CANCELED:
			$lang_key = '已取消';
			break;
		case ORDER_CONFIRM:
			$lang_key = '待确认';
			break;
	}

	return $lang_key;
}
function local_strtotime($str)
{
	$timezone = 8;

	/**
	 * $time = mktime($hour, $minute, $second, $month, $day, $year) - date('Z') + (date('Z') - $timezone * 3600)
	 * 先用mktime生成时间戳，再减去date('Z')转换为GMT时间，然后修正为用户自定义时间。以下是化简后结果
	 **/
	$time = strtotime($str) - $timezone * 3600;

	return $time;

}
function time_tran($the_time) {

	$now_time = gmtime();
	$show_time = local_strtotime($the_time);
	$dur = $now_time - $show_time;
	if ($dur < 0) {
		return local_date('m-d H:i', $show_time);
	} else {
		if ($dur < 60) {
			if(empty($dur)){
				return "刚刚";
			}  else{
				return $dur . '秒前';
			}
		} else {
			if ($dur < 3600) {
				return floor($dur / 60) . '分钟前';
			} else {
				if ($dur < 86400) {
					return floor($dur / 3600) . '小时前';
				} else {
					if ($dur < 259200) {//3天内
						return floor($dur / 86400) . '天前';
					} else {
						return local_date('m-d H:i', $show_time);
					}
				}
			}
		}
	}
}

function check_username($user_name)
{
    $model_member =& m('member');
    $info = $model_member->get("user_name='{$user_name}'");
    if (!empty($info))
    {
        $this->_error('user_exists');

        return false;
    }

    return true;
}